<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="请输入策略名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        策略添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="策略编号" prop="id" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="策略名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务组数" align="center">
        <template slot-scope="{row}">
          <span>{{ row.groupNum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="每组任务数" align="center">
        <template slot-scope="{row}">
          <span>{{ row.groupSize }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调度间隔/秒" align="center">
        <template slot-scope="{row}">
          <span>{{ row.times }}</span>
        </template>
      </el-table-column>
      <el-table-column label="策略状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.state | statusFilter">
            {{ row.state === true ? '启用':'禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
          <el-button type="info" size="mini" @click="handleDetail(row,$index)">
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-dialog
        width="30%"
        title="任务生成中....."
        :close-on-click-modal="false"
        :show-close="false"
        :visible.sync="loadingVisible"
        append-to-body="true"
      />
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        :append-to-body="true"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item v-if="['update','create'].includes(dialogStatus)" label="可用设备数" prop="countDevice">
          <el-input-number v-model="temp.countDevice" :disabled="true" :min="0" />
        </el-form-item>
        <el-form-item v-if="['update','create'].includes(dialogStatus)" label="策略名称" prop="name">
          <el-input v-model="temp.name" placeholder="请输入策略名称" />
        </el-form-item>
        <el-form-item v-if="['update','create'].includes(dialogStatus)" label="每组任务数" prop="groupSize">
          <el-input-number v-model="temp.groupSize" :min="1" :max="10000" placeholder="请输入每组任务数" />
        </el-form-item>
        <el-form-item v-if="['update','create'].includes(dialogStatus)" label="调度间隔/秒" prop="times">
          <el-input-number v-model="temp.times" :min="1" placeholder="请输入调度间隔/秒" />
        </el-form-item>
        <el-form-item v-if="['update','create'].includes(dialogStatus)" label="策略状态" prop="state">
          <el-select v-model="temp.state" class="filter-item" placeholder="请选择">
            <el-option v-for="item in statusOptions" :key="item.key" :label="item.text" :value="item.key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          生成任务
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="textMap[dialogStatus]"
      width="90%"
      :fullscreen="true"
      :visible.sync="dialogInFormVisible"
    >
      <div class="app-container">
        <el-descriptions title="策略信息">
          <el-descriptions-item label="策略名称"><el-tag size="small">{{this.temp.name}}</el-tag></el-descriptions-item>
          <el-descriptions-item label="任务组数">
            <el-tag size="small">{{this.temp.groupNum}}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="每组最大任务数"><el-tag size="small">{{this.temp.groupSize}}</el-tag></el-descriptions-item>
          <el-descriptions-item label="调度间隔/秒"><el-tag size="small">{{this.temp.times}}</el-tag></el-descriptions-item>
        </el-descriptions>
        <el-table
          :key="tableKeyDetail"
          v-loading="listLoading"
          default-expand-all
          :data="listDetail"
          style="width: 100%"
          row-key="id"
          border
          lazy
          :tree-props="{children: 'devices'}"
        >
          <el-table-column
            prop="name"
            label="组名"
            width="180"
          />
          <el-table-column
            prop="sn"
            label="设备编号"
            width="180"
          />
          <el-table-column
            prop="ip"
            label="地址"
          />
          <el-table-column
            prop="port"
            label="端口"
          />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStrategy, addStrategy, removeStrategy, modifyStrategy, getTaskByStrategyId } from '@/api/detection/schedule-manager'
import { countDevice } from '@/api/info/device'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'StrategyManager',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        true: 'success',
        false: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      tableKeyDetail: 0,
      list: null,
      listDetail: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        name: ''
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: [{ key: true, text: '启用' }, { key: false, text: '禁用' }],
      showReviewer: false,
      temp: {
        id: '',
        name: '',
        groupNum: '',
        groupSize: '',
        times: '',
        state: false
      },
      dialogFormVisible: false,
      dialogInFormVisible: false,
      loadingVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加',
        detail: '详情'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {},
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleChange(value, direction, movedKeys) {
      console.log(value, direction, movedKeys)
    },
    getList() {
      this.listLoading = true
      listStrategy(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: '',
        name: '',
        groupNum: '',
        groupSize: '',
        times: '',
        countDevice: '',
        state: false
      }
    },
    handleCreate() {
      const validatePass2 = (rule, value, callback) => {
        if (this.temp.groupSize > this.temp.countDevice) {
          callback(new Error('每组任务数不能大于设备总数!'))
        } else {
          callback()
        }
      }
      this.rules = {
        name: [{ required: true, trigger: ['blur', 'change'], message: '策略名称不能为空' }],
        groupSize: [{ validator: validatePass2, trigger: 'blur', required: true }],
        times: [{ required: true, trigger: ['blur', 'change'], message: '调度间隔时间不能为空' }],
        state: [{ required: true, trigger: ['blur', 'change'], message: '策略启用状态不能为空' }]
      }
      this.resetTemp()
      countDevice({}).then(response => {
        this.temp.countDevice = response.data
      })
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.loadingVisible = true
          addStrategy(this.temp).then(response => {
            const { data } = response
            this.temp = Object.assign({}, data) // copy obj
            this.temp.createTime = data.createTime
            if (data.state) {
              for (let i = 0; i < this.list.length; i++) {
                if (this.list[i].state) {
                  this.list[i].state = false
                  break
                }
              }
            }
            this.list.unshift(this.temp)
            this.loadingVisible = false
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 3000
            })
          })
        }
      })
    },
    handleDetail(row) {
      this.listLoading = true
      this.temp = Object.assign({}, row) // copy obj
      const param = {
        strategyId: row.id
      }
      console.log(row)
      console.log(param)
      getTaskByStrategyId(param).then(response => {
        const { data } = response
        this.listDetail = data.groups
        this.listLoading = false
      })
      this.dialogStatus = 'detail'
      this.dialogInFormVisible = true
    },
    handleUpdate(row) {
      const validatePass2 = (rule, value, callback) => {
        if (this.temp.groupSize > this.temp.countDevice) {
          callback(new Error('每组任务数不能大于设备总数!'))
        } else {
          callback()
        }
      }
      this.rules = {
        name: [{ required: true, trigger: ['blur', 'change'], message: '策略名称不能为空' }],
        groupSize: [{ validator: validatePass2, trigger: 'blur', required: true }],
        times: [{ required: true, trigger: ['blur', 'change'], message: '调度间隔时间不能为空' }],
        state: [{ required: true, trigger: ['blur', 'change'], message: '策略启用状态不能为空' }]
      }
      this.temp = Object.assign({}, row) // copy obj
      countDevice({}).then(response => {
        this.temp.countDevice = response.data
      })
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.loadingVisible = true
          modifyStrategy(this.temp).then(response => {
            const { data } = response
            this.temp = Object.assign({}, data) // copy obj
            this.temp.createTime = data.createTime
            if (data.state) {
              for (let i = 0; i < this.list.length; i++) {
                if (this.list[i].state) {
                  this.list[i].state = false
                  break
                }
              }
            }
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.total = this.total + 1
            this.loadingVisible = false
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      removeStrategy({ id: row.id }).then(() => {
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
